package com.ks.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import common.Var;

/**
 * 
 * @author 47475
 *
 */
@WebFilter(filterName = "loginFilter", urlPatterns = "/*", initParams = {
		@WebInitParam(name = "homeUI", value = "/index.html"),
		@WebInitParam(name = "loginUI", value = "/jsp/login.jsp"),
		@WebInitParam(name = "loginProcess", value = "/login"),
		@WebInitParam(name = "staticResource", value = "/static") }) // 多个过滤器安装过滤器名字排序
public class LoginFilter implements Filter {
	private static final Logger LOGGER = LoggerFactory.getLogger(LoginFilter.class);
	private FilterConfig config;

	@Override
	public void destroy() {
		LOGGER.debug("【{}】被销毁", this.getClass().getName());
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		// 获取init初始化参数
		String homeUI = config.getInitParameter("homeUI");
		String loginUI = config.getInitParameter("loginUI");
		String loginProcess = config.getInitParameter("loginProcess");
		String staticResource = config.getInitParameter("staticResource");

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
//		String uri = req.getRequestURI();// 获得用户请求的URI,除去host和port后的地址
		// req.getContextPath() 返回项目的根路径为null时""替换
		String contextPath = StringUtils.defaultIfBlank(req.getContextPath(), "");
		// 获得完整url不包括参数
		StringBuffer lastAccessUrl = req.getRequestURL();
		// 获得地址栏请求参数,拼接到URL上
		String lastAccessUrlParams = req.getQueryString();
		if (StringUtils.isNotBlank(lastAccessUrlParams)) {
			lastAccessUrl.append("?");
			lastAccessUrl.append(lastAccessUrlParams);
		}
		String loginPagePath = contextPath + loginUI;
		// 请求的action,比uri少一个contextPath
		String servletPath = req.getServletPath();
		if (servletPath.startsWith(homeUI)) {
			LOGGER.debug("访问主页面【{}】放行，不创建sesssion", servletPath);
			chain.doFilter(request, response);
			return;
		}

		// 在这里创建session为了统计网站的访问人数（不是登录人数）
		HttpSession session = req.getSession(false);

		// 请求的地址是下面的直接放行,不需要拦截的页面
		if (servletPath.startsWith(homeUI) || servletPath.startsWith(loginUI) || servletPath.startsWith(loginProcess)
				|| servletPath.startsWith(staticResource) || servletPath.startsWith("/login.html")
				|| servletPath.startsWith("/generateRSAKey") || servletPath.startsWith("/public")
				|| servletPath.startsWith("/dwr") || servletPath.startsWith("/jsp/register.jsp")
				|| servletPath.startsWith("/register") || servletPath.startsWith("/favicon.ico")
				|| servletPath.startsWith("/check")) {
			LOGGER.debug("请求的资源【{}】不需要拦截放行", servletPath);
			chain.doFilter(request, response);
			return;
		}

		LOGGER.debug("***请求的ServletPath【{}】***", servletPath);
		if (session == null || session.getAttribute(Var.USER_INFO) == null) {
			LOGGER.debug("***用户未登陆，跳转到登录页面***");
			res.sendRedirect(loginPagePath);
			return;
		} else {
			LOGGER.debug("***用户登录放行***");
			chain.doFilter(request, response);
			return;
		}
		// 如果Session中没有用户信息并且请求的不是登陆页面(上面其实已经放行了登陆页面，这里只是测试)
//		if (session.getAttribute("user") == null) {
//			// 判断如果没有登录,就跳转到登陆页面
//			LOGGER.info("***用户未登陆***");
//			res.sendRedirect(loginPagePath);
//		} else {// 已经登陆,继续此次请求
//			chain.doFilter(request, response);
//		}
//		if (!StringUtils.equals(loginPagePath, uri) && session.getAttribute("sys.username") == null) {
//			// AJAX请求
//			if (req.getHeader("x-requested-with") != null
//					&& req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
//
//				String divLoad = req.getParameter("divLoad");
//				PrintWriter printWriter = res.getWriter();
//				if ("true".equals(divLoad)) {
//					printWriter.write(
//							"<script type='text/javascript'>window.top.location='" + loginPagePath + "'</script>");
//
//				} else {
//					printWriter.print("{sessionState:0}");
//				}
//				printWriter.flush();
//				printWriter.close();
//
//			} else if (StringUtils.startsWith(uri, mainUrl)) {
//				res.sendRedirect(loginPagePath);
//			} else {
//				// 普通请求
//				res.sendRedirect(loginPagePath);
//			}
//			return;
//		} else {
//			chain.doFilter(request, response);
//		}

	}

	public void init(FilterConfig fConfig) throws ServletException {
		LOGGER.debug("【{}】初始化", this.getClass().getName());
		this.config = fConfig;
	}

}
